package com.situ.mall.controller.front;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AliPayController {
    //!!!!!注意这里是你的APPID沙箱里查看
    //应用id
    private final static String APP_ID="2016093000630167";

    //!!!!!注意这里是你的应用私钥，在支付宝开发平台助手里（就是刚才生成的私钥）
    //应用私钥
    private final static String APP_PRIVATE_KEY="MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCrp13YjrTfwDpiZy82qzJUyom+zZDaiPDX1zKddWWUTLRYJ5bX5Te1TXSUHcw5sHpBfcvJAbvxpAY9eUN0StDcvgv5d8xTjFl3RJ4dLn+IkaZokW/YTHWg1nL0Mc7uUIAL3OJKce/ldqKHqlSrAI2/Uljb3VOHNBNLUuwja2F0DcONou0DJZIJwu46C34lyDBjPAxKYNtEiM1z6dIiE0b009O3DWjrjOVrji81xEbC3wcyaB0aMOoIPsAyMbt6OaP0TjMM01LPoAHBnPn1pE2AQiyGoCWOqnlfML5i5qGg1f4il0A0tpl4Xeg42AplnnrO5dfqgD9hRNuPhdQT56I9AgMBAAECgf9TJL5QJs91kaa2A0TbNhErAO+3e9qt/6ao5ZOesT6ClqTEDmkCKgTRzLKrC8PgLZsKHeSXeD+Qy+I55ILH0XVZdrRWIbDWxySOoK31dJBRljsEa23BV0eioD0OCxIwXM2o8VSquoV4n/4ZuGdKbPo7sadY19udoZu24HOAtIJ/s18odfkUeQnqrF/elDPgf9BnEStuxXuGkZoJdLMtW3kmZhIolFsvSpefiCnvbKZb4u498cL4Q2lsK62dtCV4z1yBcCTzcaLUhzisKFZb1zYlodYG4oudela7MGR4Tfvrvoy+CmSkkFWOUG7c6Kyjxw9r8RRfKpS1i5POg5ufWpECgYEA5OfiaI/4BWljHKLK09O/wEuZnKd9roytpgPsZdpo9WotB0ZpzMY9MunnDkI6UEKhykPcoTkgz2KNMT7IpMLOjFJVEMcACrrWzYaf1ARYHMSB8dXq2F+w6xMpCoLiI4YStqsNaiL3GJ7yPXm0SDDBwQVp0YsW2bEy9o1o9YOBX6sCgYEAv/itqo8pLNrGcYCjnP4A0VPAOO1U5elMcIJzpMeMEo8LgPeN5vR9k7cS7F++brCuMEeTvA5uSLcSYfjQzhiKZ39KX2e1Kpy0c9DqjBo4brHAQ6b2Lz9xZJMyzVpzCgatqY8YAhPmxsux4h93S2V6P5G9DfvOqAJj4jeZ8u1hvbcCgYAiZ1+2C31hgtdspGMLt1WolzQ9QUc4hthKjWhoXo1L5WtjHogkSN9F2bXqhLWy/nDGr7BnYui1gsBp2F/bs5PLr0wtu1scQbyrI0K+YPDFUhudt2MWpjs2+ag/djB62lnRrp/ThfHRd4I9Dx+zgfB9DE09O0Rx75oTSGmwDNXTBQKBgCrqchCOHptbcT+QjYMcOZySR4eybudTB3ajgyzUO1kux1iWfw+hmq06IS3cnZrrPpWmer1w0HDLFH34fN2GGPLYPw0jBxo2nBTEIJsfhXwhmqTFH4YifbwJODM2RD96jLo6NhjI0C+i++pcNHQThIfPkd8dau6eUiwRWAY50T7zAoGBANZ76oluG9fRfUPzlwEF636u5pUuDGxI0Y0BkPB5jWKrrX73XkaY3KdVgotwuhV03e19Z4D98KlY8XqdVGZmDRnuHuUSUoAIV6jtxWfYegL49bnrgH/E6d8/8etszixUWrSaGLh0Tf7uCR2L6f+hXyFksxNeuL242oeFRTdp2Ca/";
    //字符集
    private final static String CHARSET="UTF-8";

    //!!!!!注意这里是你的支付宝公钥，在沙箱环境中RSA2(SHA256)密钥 弹窗里面的,支付宝公钥
    //应用公钥
    private final static String ALIPAY_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArppNXJqggEa2cZoBFcCb431QAAeraMbtqTG9WSeRLSTiwV2aGqCuaCKUeXkSaqUqWWRG9uRxiwNrs6pPwIj2X33xWx5CKrc5CPplanyPRFtM3jeEgzg8V80wXqvq74OkIDhXauMott6O2cOyNYvSDDwtKjKEEx57vbaiGqzg7kRIkU3D30NDry4fzLSzoDAW13FJ2t/QNRLUAaONJUgDTC823KDfpvHxyDLa6uv4D10+jccWwQt/G2FUuWN07+YY4ZEDS/hTjoXpVOaYSZ16YfiW8iSRKvzfHQdU7goMr233OY99ghOzLwVXigkzzHgegpyaDhTqu4eI1PMfbiUzcQIDAQAB";

    //!!!!!注意这里是你的支付宝网关，在沙箱环境里查看
    //网关
    private final static String GATEWAY_URL="https://openapi.alipaydev.com/gateway.do";

    //格式化
    private final static String FORMAT="json";
    //签名类型
    private final static String SIGNTYPE="RSA2";
    /*
     * 获取订单信息
     * */
    @GetMapping("getOrderInfo")
    public String getOrderInfo() {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo("这里是交易订单号");
        model.setTimeoutExpress("30m");
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("商户外网可以访问的异步地址");
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/notify_url")
    public String notify_url(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {

            boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET,SIGNTYPE);
            //如果验签失败
            if(!flag){
                return "fail";
            }
            //验签成功后
            //商户的业务逻辑  比如修改订单号
            System.out.println("修改订单成功");

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }


    //这里是main方法用来生成alipay_sdk信息
    public static void main(String[] args) {
        AliPayController aliPayController = new AliPayController();
        aliPayController.getOrderInfo();
    }
}
